response.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from __future__ import absolute_import
  2. from ..packages.six.moves import http_client as httplib
  3. from ..exceptions import HeaderParsingError
  4. def is_fp_closed(obj):
  5. """
  6. Checks whether a given file-like object is closed.
  7. :param obj:
  8. The file-like object to check.
  9. """
  10. try:
  11. # Check `isclosed()` first, in case Python3 doesn't set `closed`.
  12. # GH Issue #928
  13. return obj.isclosed()
  14. except AttributeError:
  15. pass
  16. try:
  17. # Check via the official file-like-object way.
  18. return obj.closed
  19. except AttributeError:
  20. pass
  21. try:
  22. # Check if the object is a container for another file-like object that
  23. # gets released on exhaustion (e.g. HTTPResponse).
  24. return obj.fp is None
  25. except AttributeError:
  26. pass
  27. raise ValueError("Unable to determine whether fp is closed.")
  28. def assert_header_parsing(headers):
  29. """
  30. Asserts whether all headers have been successfully parsed.
  31. Extracts encountered errors from the result of parsing headers.
  32. Only works on Python 3.
  33. :param headers: Headers to verify.
  34. :type headers: `httplib.HTTPMessage`.
  35. :raises urllib3.exceptions.HeaderParsingError:
  36. If parsing errors are found.
  37. """
  38. # This will fail silently if we pass in the wrong kind of parameter.
  39. # To make debugging easier add an explicit check.
  40. if not isinstance(headers, httplib.HTTPMessage):
  41. raise TypeError("expected httplib.Message, got {0}.".format(type(headers)))
  42. defects = getattr(headers, "defects", None)
  43. get_payload = getattr(headers, "get_payload", None)
  44. unparsed_data = None
  45. if get_payload:
  46. # get_payload is actually email.message.Message.get_payload;
  47. # we're only interested in the result if it's not a multipart message
  48. if not headers.is_multipart():
  49. payload = get_payload()
  50. if isinstance(payload, (bytes, str)):
  51. unparsed_data = payload
  52. if defects or unparsed_data:
  53. raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
  54. def is_response_to_head(response):
  55. """
  56. Checks whether the request of a response has been a HEAD-request.
  57. Handles the quirks of AppEngine.
  58. :param conn:
  59. :type conn: :class:`httplib.HTTPResponse`
  60. """
  61. # FIXME: Can we do this somehow without accessing private httplib _method?
  62. method = response._method
  63. if isinstance(method, int): # Platform-specific: Appengine
  64. return method == 3
  65. return method.upper() == "HEAD"